import { h, render } from 'vue';
import { getChatDataUnified, getCurrentChatId } from './whatsappHandler';
import OrderInfoBar from '../components/OrderInfoBar.vue';

interface ChatData {
  order_no?: string;
  name?: string;
  status?: string;
  order_note?: string;
  remark?: string;
  remarks?: any[];
  created_at?: string;
  operation_suggestion?: string;
  follow_status?: string;
  nickname?: string;
  ChatRemind?: {
    success?: boolean;
    viewed?: boolean;
    content?: string;
    [key: string]: any;
  };
}

interface Customer {
  _serialized?: string;
  id?: string;
  [key: string]: any;
}

interface ChatDataHandlerOptions {
  onStatusChange?: (status: string) => void;
  onShowModifyInfo?: (chatId: string) => void;
  onShowAiReply?: (data: any) => void;
  onError?: (message: string) => void;
}

export async function handleChatDataUpdate(
  chatId: string | Customer, 
  forceRefresh: boolean = false,
  options: ChatDataHandlerOptions = {}
): Promise<ChatData | null> {

  // 支持传入customer对象或直接传入chatId
  const actualChatId = typeof chatId === 'object' && chatId?._serialized ? chatId._serialized : chatId as string;
  
  // 添加处理标记，防止重复处理
  const processingKey = `processing-${actualChatId}`;
  if ((window as any)[processingKey]) {
    return null;
  }

  try {
    // 设置处理标记
    (window as any)[processingKey] = true;

    // 强制刷新时，先清除缓存数据
    if (forceRefresh) {
      try {
        // 导入clearCachedOrderData函数
        const { clearCachedOrderData } = await import('./whatsappHandler');
        await clearCachedOrderData(actualChatId);
      } catch (error) {
        console.error('清除缓存数据失败:', error);
      }
    }

    // 获取聊天数据
    const data = await getChatDataUnified(actualChatId, forceRefresh);

    if (!data) {
      // 没有数据时，隐藏infobar
      hideOrderInfoBar();
      return null;
    }

    // 处理状态更新
    const status = data.follow_status || '';
    if (status && options.onStatusChange) {
      options.onStatusChange(status);
    }

    // 处理订单信息栏
    if (data.order_no) {
      await handleOrderInfoBar(data, actualChatId, options);
    } else {
      // 没有订单号时，隐藏infobar
      hideOrderInfoBar();
    }

    // 处理AI回复提醒
    if (data.ChatRemind?.success && data.ChatRemind.viewed === false) {
      await handleAiReply(data, actualChatId, options);
    }

    return data;
  } catch (error) {
    console.error('处理聊天数据更新出错:', error);
    options.onError?.('获取聊天数据失败');
    return null;
  } finally {
    // 清除处理标记
    setTimeout(() => {
      delete (window as any)[processingKey];
    }, 1000);
  }
}

async function handleOrderInfoBar(data: ChatData, chatId: string, options: ChatDataHandlerOptions) {
  // 如果没有订单号，则隐藏订单信息栏并返回
  if (!data.order_no) {
    hideOrderInfoBar();
    return;
  }
  
  // 找到或创建容器
  let container = document.querySelector('#main header + .order-info-container');
  if (!container) {
    const header = document.querySelector('#main header');
    if (!header) {
      console.error('未找到 header 元素');
      return;
    }
    
    container = document.createElement('div');
    container.className = 'order-info-container';
    header.parentNode?.insertBefore(container, header.nextSibling);
  } else {
    // 检查是否需要更新
    const currentOrderNo = container.getAttribute('data-order-no');
    if (currentOrderNo === data.order_no && container.innerHTML !== '') {
      return;
    }
    
    // 清空现有容器内容，准备重新渲染
    container.innerHTML = '';
  }

  if (container) {
    // 确保容器可见
    (container as HTMLElement).style.display = 'block';
    
    // 记录当前处理的订单号，用于验证数据一致性
    container.setAttribute('data-order-no', data.order_no || '');
    
    // 渲染 OrderInfoBar 组件
    const orderInfoBar = h(OrderInfoBar, {
      orderNo: data.order_no,
      orderName: data.name,
      orderStatus: data.status,
      orderNote: data.order_note,
      orderRemark: data.remark || '',
      remarks: data.remarks || [],
      createdAt: data.created_at,
      operationSuggestion: data.operation_suggestion,
      chatId: chatId,
      onClose: () => {
        hideOrderInfoBar();
      },
      onFollow: () => {
        options.onShowModifyInfo?.(chatId);
      }
    });

    render(orderInfoBar, container);
  }
}

async function handleAiReply(data: ChatData, chatId: string, options: ChatDataHandlerOptions) {
  try {
    const current_chat_id = getCurrentChatId();
    if (current_chat_id !== chatId) {
      return;
    }

    if (data.ChatRemind?.content) {
      const structuredData = parseResponse(data.ChatRemind.content);
      if (structuredData) {
        options.onShowAiReply?.(structuredData);
      }
    }
  } catch (error) {
    console.error('处理 AI 回复出错:', error);
  }
}

function parseResponse(raw: string) {
  try {
    const jsonStart = raw.indexOf('{');
    const jsonEnd = raw.lastIndexOf('}') + 1;
    const jsonString = raw.slice(jsonStart, jsonEnd);
    
    const decodedString = jsonString.replace(/\\u([\d\w]{4})/gi,
      (match, grp) => String.fromCharCode(parseInt(grp, 16))
    );

    let structuredData = JSON.parse(decodedString);
    if (structuredData['回复建议'] && Array.isArray(structuredData['回复建议'])) {
      structuredData['回复建议'] = structuredData['回复建议'].reverse();
    }
    return structuredData;
  } catch (error) {
    console.error('解析失败:', error);
    return null;
  }
}

export function hideOrderInfoBar() {
  // 检查是否有正在进行的 OrderInfoBar 处理
  if ((window as any).hideOrderInfoBarProcessing) {
    return;
  }
  
  // 设置处理标记
  (window as any).hideOrderInfoBarProcessing = true;
  
  try {
    const container = document.querySelector("#main header + .order-info-container");
    if (container) {
      // 清空内容
      container.innerHTML = '';
      // 隐藏容器
      (container as HTMLElement).style.display = 'none';
      // 清除订单号属性
      container.removeAttribute('data-order-no');
      // 清除聊天ID属性
      container.removeAttribute('data-chat-id');
      
      // 延迟检查，确保容器确实被隐藏
      setTimeout(() => {
        const containerCheck = document.querySelector("#main header + .order-info-container");
        if (containerCheck && (containerCheck as HTMLElement).style.display !== 'none') {
          (containerCheck as HTMLElement).style.display = 'none';
        }
        
        // 清除处理标记
        (window as any).hideOrderInfoBarProcessing = false;
      }, 200);
    } else {
      // 清除处理标记
      (window as any).hideOrderInfoBarProcessing = false;
    }
  } catch (error) {
    console.error('hideOrderInfoBar: 处理出错:', error);
    // 确保处理标记被清除
    (window as any).hideOrderInfoBarProcessing = false;
  }
} 